package com.xiaoc.bulldozer.common.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author wj
 */
public class WebUtils {

    public static final ObjectMapper mapper = new ObjectMapper();

    public static String formatObject(Object obj){
    	try {
    		mapper.enable(SerializationFeature.INDENT_OUTPUT);
    		return mapper.writeValueAsString(obj);
		} catch (Exception e) {
			return "";
		}
    }
    
	public static void responseJson(HttpServletResponse response, Object obj){
		mapper.setSerializationInclusion(Include.NON_NULL);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if(obj instanceof  String){
				out.println(obj);
			}else{
				out.println(mapper.writeValueAsString(obj));
			}
			out.flush();
		} catch(Exception e){
			e.printStackTrace();
		}finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	public static String getFullContextPath(HttpServletRequest request){
		String fullUrl = request.getRequestURL().toString();
		String contextPath = request.getContextPath();
		String path = fullUrl.substring(0, fullUrl.indexOf(contextPath)) +  contextPath;
		return path.replace("http", "https");
		
		/*String path = request.getContextPath();
		StringBuilder builder = new StringBuilder();
		builder
		   .append(request.getScheme())
		   .append("://")
		   .append(request.getServerName())
		   .append(":")
		   .append(request.getServerPort())
		   .append(path)
		   .append("/");
		return builder.toString();*/
	}
}
